package com.cuitrip.business.webview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.fastjson.JSONObject;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.I118Util;
import com.lab.app.BaseActivity;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.logtrack.AppLog;
import com.lab.schemeurl.SchemeUrlHandler;
import com.lab.schemeurl.constant.Scheme;
import com.lab.utils.ToastUtil;

import java.lang.ref.WeakReference;
import java.util.Iterator;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by ak
 */
public class WebBrowserActivity extends CustomUiFragmentActivity implements View.OnClickListener {

    public static final String PARAM_WEB_PARAM = "param_web_param";
    public static final String PARAM_URL = "param_url";
    public static final String PARAM_OBJECT = "param_object";
    public static final String PARAM_WEB_TITLE = "PARAM_WEB_TITLE";
    public static final String PARAM_USE_WEB_TITLE = "PARAM_USE_WEB_TITLE";
    private static final String TAG = "WebBrowserActivity";
    private static final int MAX_WEB_LOADING_PROGRESS = 100;
    @Bind(R.id.refresh_layout)
    protected SwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.webView)
    protected WebView mWebView;
    protected String mStringObject;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;
    private String mUrl;
    private WebParam mWebParam;

    private WebHandler mWebHandler = new WebHandler(this);
    private String webTitle;
    private boolean useWebTitle;

    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (null != intent) {
            Bundle bundle = intent.getExtras();
            if (null != bundle) {
                mUrl = bundle.getString(PARAM_URL);
                mWebParam = bundle.getParcelable(PARAM_WEB_PARAM);
                mStringObject = bundle.getString(PARAM_OBJECT);
                webTitle = bundle.getString(PARAM_WEB_TITLE, "");
                useWebTitle = bundle.getBoolean(PARAM_USE_WEB_TITLE, false);
            }
        }
        if (TextUtils.isEmpty(mUrl)) {
            ToastUtil.toast("Url地址无效");
            Jumper.finishActivity(this);
            return;
        }
        super.onCreate(savedInstanceState, R.layout.web_browser_activity);
    }

    @Override
    public void initListener() {
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                reload();
            }
        });
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarRightPress() {
        finish();
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = "";
        config.mTopbarRightAreaName = getString(R.string.clear_icon);
        config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        return config;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mWebView) {
            mWebView.setVisibility(View.GONE);
            ViewGroup parent = (ViewGroup) mWebView.getParent();
            if (null != parent)
                parent.removeView(mWebView);
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }


    public void initView() {
        ButterKnife.bind(this);
        mRefreshLayout.setEnabled(false);
        mTopbarLeftArea.setVisibility(View.GONE);


        /*mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    if (null != mWebView) {
                        mWebView.clearCache(true);
                        mWebView.clearHistory();
                    }
                } catch (Exception e) {
                    AppLog.w(e.getMessage());
                reload();
            }
        });*/


        // 构建JS调用接口
        WebViewJsListener webViewJsListener = new WebViewJsListener() {
            @Override
            public void showToast(final String message) {
                mWebHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.toast(message);
                    }
                });
            }

            @Override
            public void setTitle(final String title) {
                mWebHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateTitle(title);
                    }
                });
            }
        };
        WebViewMusicianJsInterface webViewMusicianJsInterface = new WebViewMusicianJsInterface(webViewJsListener);

        // 构建WebView配置WebSetting
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        // 开启用户缩放控制,默认载入时为显示全部
        webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        // 启用地理定位
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setLoadsImagesAutomatically(true);

        // 配置WebView
        mWebView.addJavascriptInterface(webViewMusicianJsInterface, WebViewMusicianJsInterface.JS_INSIDER);

        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setBackgroundColor(0x00000000);
        mWebView.setWillNotCacheDrawing(false);
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                boolean result = performShouldOverrideUrlLoading(webView, url);
                // 已处理,关闭当前Web页面
                /*if (result) {
                    Jumper.finishActivity(WebBrowserActivity.this);
                }*/
                return result;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                mRefreshLayout.setRefreshing(true);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                mRefreshLayout.setRefreshing(false);
                updateTitle(view.getTitle());
                mStateLayout.changeState(StateLayout.State.INIT);
                if (null != mWebView && mWebView.canGoBack()) {
//                    showCloseUI();
                } else {
//                    hideCloseUI();
                }
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                mStateLayout.changeState(StateLayout.State.NoNetwork);
                mRefreshLayout.setRefreshing(false);
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                updateTitle(title);
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }

            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
            }

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                transport.setWebView(mWebView);
                resultMsg.sendToTarget();
                return true;
            }

        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (!TextUtils.isEmpty(url)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    Jumper.launchActivity(WebBrowserActivity.this, intent);
                }
            }
        });
        mWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    int tempScrollY = view.getScrollY();
                    view.scrollTo(view.getScrollX(), view.getScrollY() + 1);
                    view.scrollTo(view.getScrollX(), tempScrollY);  //返回原来位置，可不加
                }
                if (null != mWebView) {
                    mWebView.requestFocus();
                }
                return false;
            }
        });

    }

    public void initData() {
        load(mUrl);
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (null != mWebView && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View view) {

    }

    private void closeBrowser() {
        Jumper.finishActivity(this);
    }

    private boolean performShouldOverrideUrlLoading(WebView webView, String url) {
        AppLog.d(TAG + " performShouldOverrideUrlLoading url = " + url);
        boolean result = false;
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            String schemeName = uri.getScheme();
            Scheme scheme = Scheme.getSchemeByName(schemeName);
            if (null != scheme) {
                if (scheme == Scheme.CUITRIP) {
                    result = SchemeUrlHandler.getInstance().dispatch(this, uri, webView);
                    // 判断是否需要Keep页面
                    /*String status = uri.getQueryParameter(SchemeParam.KEY_STATUS);
                    if (null != status && status.equals(SchemeParam.STATUS_KEEP_PAGE)) {
                        result = false;
                    }*/
                    result = true;
                }
            }
        }
        AppLog.d(TAG + " performShouldOverrideUrlLoading result = " + result);
        return result;
    }

    private void load(String url) {
        if (null != mWebView) {
            AppLog.d(TAG + " load url = " + url);
            setCookies();
            mStateLayout.changeState(StateLayout.State.Loading);
            if (com.lab.network.util.NetworkUtil.getConnectState(this) == com.lab.network.util.NetworkUtil.CONNECT_NONE) {
                mStateLayout.changeState(StateLayout.State.NoNetwork);
            } else {
                if (mStringObject != null) {
                    JSONObject jsonObject = JSONObject.parseObject(mStringObject);
                    if (jsonObject.containsKey("sid")) {
                        String sid = jsonObject.getString("sid");
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append("?").append("lang").append("=").append(I118Util.getLanguageTag());
                        if (jsonObject.containsKey("isDraft")){
                            stringBuilder.append("&");
                            stringBuilder.append("isDraft").append("=").append(jsonObject.getString("isDraft"));
                        }
                        mWebView.postUrl(url + "/" + sid + stringBuilder.toString(), null);
                    } else {
                       Iterator<String> iterator = jsonObject.keySet().iterator();
                        StringBuilder urlParams = new StringBuilder();
                        while (iterator.hasNext()){
                            String key = iterator.next();
                            if (urlParams.length() == 0){
                                urlParams.append("?");
                            }else{
                                urlParams.append("&");
                            }
                            urlParams.append(key).append("=").append(jsonObject.getString(key));
                        }
                        mWebView.postUrl(url + urlParams.toString(), null);
                    }
                } else {
                    mWebView.loadUrl(url);
                }
            }

        }
    }

    private void reload() {
        if (null != mWebView) {
            AppLog.d(TAG + " reload");
            setCookies();
            mWebView.reload();
        }
    }

    private void setCookies() {
        try {
            CookieSyncManager.createInstance(this);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            CookieSyncManager.getInstance().sync();
        } catch (Exception e) {
            AppLog.w(e.getMessage());
        } catch (Error e) {
            AppLog.w(e.getMessage());
        }
    }

    private void updateTitle(String title) {
        if (useWebTitle) {
            mTopbarMiddleArea.setText(this.webTitle);
        } else {
            mTopbarMiddleArea.setText(title);
        }
    }

    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

    private class WebHandler extends Handler {

        WeakReference<WebBrowserActivity> reference;

        public WebHandler(WebBrowserActivity activity) {
            reference = new WeakReference<WebBrowserActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BaseActivity activity = reference.get();
            if (null == activity)
                return;
            switch (msg.what) {
            }
        }
    }
}
